package com.calvin.study.multithread.threadutils;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.calvin.study.utils.ThreadUtil;

import cn.hutool.core.util.RandomUtil;

//Semaphore用来控制在同一时刻访问共享资源的线程数量（使用了排它锁）
public class SemaphoreDemo {

	static int spot = 3;
	
	public static void main(String[] args) {
		 park();
	}
	public static void park() {
		// 模拟3个停车位
		Semaphore semaphore = new Semaphore(3);
		// 模拟6部汽车
		for (int i = 1; i <= 6; i++) {
			new Thread(() -> {
				try {
					// 抢到资源
					semaphore.acquire();
					System.out.println(Thread.currentThread().getName() + "\t抢到车位");
					try {
						int stopTime  = RandomUtil.randomInt(1, 3);
						TimeUnit.SECONDS.sleep(stopTime);
						System.out.println(Thread.currentThread().getName() + "\t 停"+stopTime+"秒离开车位");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					// 释放资源
					semaphore.release();
				}
			}, String.valueOf(i)).start();
		}
	}
}
